package alarmapi

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	"gitee.com/haodreams/libs/ee"
)

var alarmUrl string

type Event struct {
	Owner   string
	Group   string
	Module  string
	Level   int
	Message string
}

/**
 * @description: 设置报警的路径
 * @param {string} url
 * @return {*}
 */
func Setup(url string) {
	alarmUrl = url
}

/**
 * @description: 发送一个报警
 * @param {*Event} e
 * @return {*}
 */
func SendAlarm(e *Event) (err error) {
	client := http.Client{}
	client.Timeout = time.Duration(time.Second*30) * time.Millisecond

	if strings.HasPrefix(alarmUrl, "https://") {
		tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
		client.Transport = tr
	}

	postData, err := json.Marshal(e)
	if err != nil {
		return
	}

	request, err := http.NewRequest("POST", alarmUrl, bytes.NewBuffer(postData))
	if err != nil {
		err = ee.New(err)
		return
	}
	//设置头部Second
	request.Header.Add("Content-Type", "application/json; charset=utf-8")

	rsp, err := client.Do(request)
	if err != nil {
		err = ee.New(err)
		return
	}

	if rsp.StatusCode != http.StatusOK {
		err = ee.NewError(fmt.Sprintf("Status code:%d", rsp.StatusCode))
		return
	}
	return
}
